package org.freez4.spring.dependency.lookup;

import org.freez4.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * {@link ObjectProvider} 延迟查找。
 *
 * @author 阿坤同学
 * @date 2023/12/7 11:06 AM
 */
public class ObjectProviderDemo {

    private static final Logger logger = Logger.getLogger(ObjectProviderDemo.class.getName());

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(ObjectProviderDemo.class);
        applicationContext.refresh();

        lookupByObjectProvider(applicationContext);
        lookupByStreamOps(applicationContext);
        lookupIfAvailable(applicationContext);
        applicationContext.close();
    }


    @Bean
    public String helloWorld() {
        return "hello,World!";
    }

    private static void lookupByObjectProvider(ApplicationContext applicationContext) {
        ObjectProvider<String> objectProvider = applicationContext.getBeanProvider(String.class);
        logger.log(Level.INFO, () -> "ObjectProvider单一延迟查找demo:" + objectProvider.getObject());
    }


    /**
     * {@link ObjectProvider#stream()} Stream使用
     *
     * @param applicationContext IOC
     * @author 阿坤同学
     * @date 2023/12/7 5:27 PM
     */
    private static void lookupByStreamOps(AnnotationConfigApplicationContext applicationContext) {
        ObjectProvider<String> objectProvider = applicationContext.getBeanProvider(String.class);
        objectProvider.stream().forEach(str -> logger.log(Level.INFO, () -> str));
    }

    /**
     * {@link ObjectProvider#ifAvailable(Consumer)} Java8 lambda扩展
     *
     * @param applicationContext BeanFactory
     * @author 阿坤同学
     * @date 2023/12/7 5:27 PM
     */
    private static void lookupIfAvailable(AnnotationConfigApplicationContext applicationContext) {
        ObjectProvider<User> userObjectProvider = applicationContext.getBeanProvider(User.class);
        User user = userObjectProvider.getIfAvailable(User::createUser);
        logger.log(Level.INFO, () -> "当前 User 对象：" + user);
    }

}
